package cc.avatar.repository;

import java.util.Date;
import java.util.List;

import cc.avatar.model.AccountingEntry;
import cc.avatar.model.AccountingRole;
import cc.avatar.model.Party;
import cc.avatar.model.PersistentPostingRule;
import cc.avatar.model.dao.PartyDao;
import cc.avatar.util.DateUtil;

public class PartyRepository {
	
	private PartyDao partyDao;
	
	public void setPartyDao(PartyDao partyDao) {
		this.partyDao = partyDao;
	}

	public void saveParty(Party p){
		partyDao.save(p);
	}
	
	public List<Party> getAllPartyByRole(AccountingRole role){
		return partyDao.getAllPartyByRole(role);
	}
	
	public List<Party> getAllActivePartyByRole(AccountingRole role){
		return partyDao.getAllActivePartyByRole(role);
	}
	
	public List<Party> getAll(){
		return partyDao.getAll();
	}
	
	public void addRule(Long id, PersistentPostingRule rule){
		Party p = this.getPartyById(id);
		p.addRule(rule);
		this.saveParty(p);
	}
	
	public Party getPartyById(Long id){
		return partyDao.getById(id);
	}
	
	@SuppressWarnings("unchecked")
	public List<AccountingEntry> findAccountingEntriesByMonth(Long partyId, int year, int month){
		String hql = "from AccountingEntry e where e.party.id =? and e.date between ? and ? ";
		Date day = DateUtil.getBeginningOfMonth(year, month);
		return partyDao.getHibernateTemplate().find(hql, 
				new Object[]{partyId, 
				day, 
				DateUtil.addOneMonth(day)});
	}

	@SuppressWarnings("unchecked")
	public List<AccountingEntry> findAccountingEntriesByDay(Long partyId, Date day){
		String hql = "from AccountingEntry e where e.party.id =? and e.date between ? and ? ";		
		return partyDao.getHibernateTemplate().find(hql, 
				new Object[]{partyId, 
				day, 
				DateUtil.addOneDay(day)});
	}
}
